package com.example.qxfw.mongodb.hy.controller;

import com.example.qxfw.common.SysResult;
import com.example.qxfw.mongodb.hy.entity.HyAridWarnAnalysisFile;
import com.example.qxfw.mongodb.hy.service.GridWarnAnalysisFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;

@Api(tags = "Mongo服务库-地灾预警分析格点文件")
@RestController
@CrossOrigin
@RequestMapping("/hy/gridWarnAnalysisFile")
public class GridWarnAnalysisFileController {

    @Autowired
    private GridWarnAnalysisFileService gridWarnAnalysisFileService;

    @ApiOperation("根据tableId获取文件")
    @GetMapping("/getByTableId")
    public void getByTableId(String tableId, HttpServletResponse response) throws IOException {
        HyAridWarnAnalysisFile file = gridWarnAnalysisFileService.getByTableId(tableId);
        InputStream inputStream = new ByteArrayInputStream(file.getData());

        //保存文件
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String filePath = applicationHome.getDir().getParentFile()
                .getParentFile().getAbsolutePath() + "\\src\\main\\resources\\grids";
        OutputStream out = Files.newOutputStream(Paths.get(filePath + "\\1公里基础GRID.grid"));


        //响应
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getTable_id(), "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
            out.write(b,0,len);
        }
        inputStream.close();
    }

    @ApiOperation("判断文件是否存在")
    @GetMapping("/isExist")
    public SysResult isExist(String tableId){
        Boolean exist = gridWarnAnalysisFileService.isExist(tableId);
        return SysResult.success(exist);
    }


}
